package example.demo;

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.RestTemplate;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.concurrent.CountDownLatch;

@SpringBootTest
@RunWith(SpringRunner.class)
@Slf4j
public class DemoMiDeng {

    @Autowired
    RestTemplate restTemplate;

    int count = 100;
    CountDownLatch latch = new CountDownLatch(count);
    CountDownLatch testLatch = new CountDownLatch(count);

    @Autowired
    JdbcTemplate jdbcTemplate;


    @Test
    public void testMiDeng() throws InterruptedException {
        List<Integer> query1 = jdbcTemplate.query("select age from tb_user where id=1", new RowMapper<Integer>() {
            @Override
            public Integer mapRow(ResultSet rs, int rowNum) throws SQLException {
                return rs.getInt("age");
            }
        });
        Integer integer1 = query1.get(0);
        System.err.println("start==开始的年龄==" + integer1);
        for (int i = 0; i < count; i++) {
            new Thread(() -> {
                try {
                    latch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                String url = "http://localhost:8080/rao/mi-deng/MiDengController/updateIncrAge/1";
                String result = restTemplate.getForObject(url, String.class);
                log.info(Thread.currentThread().getName() + "===" + result);
                testLatch.countDown();
            }).start();
            latch.countDown();
        }
        testLatch.await();
        List<Integer> query2 = jdbcTemplate.query("select age from tb_user where id=1", new RowMapper<Integer>() {
            @Override
            public Integer mapRow(ResultSet rs, int rowNum) throws SQLException {
                return rs.getInt("age");
            }
        });
        Integer integer2 = query2.get(0);
        System.err.println("end==100次重复请求的年龄==" + integer2);
    }
}
